package com.lagou.client;

import io.netty.channel.Channel;
import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 维护与服务端的连接会话
 */
public class ClientSessions {
    Logger logger = LoggerFactory.getLogger(getClass().getName());

    private ClientSessions() {

    }


    private static class Holder {
        public static final ClientSessions instance = new ClientSessions();
    }

    public static ClientSessions getInstance() {
        return Holder.instance;
    }

    private ConcurrentHashMap<String, Channel> sessions = new ConcurrentHashMap<>();

    public void addClientSession(String ipAndPort, Channel session) {
        sessions.put(ipAndPort, session);
    }

    public void removeByIp(String ipAndPort) {
        sessions.remove(ipAndPort);
    }

    public Channel getSessionByIp(String ipAndPort) {
        return sessions.get(ipAndPort);
    }

    //根据响应时间获取
    public Channel getSessionByLb(CuratorFramework zkclient) {

        long minRespontime=Integer.MAX_VALUE;
        Channel c = null;

        logger.info("当前连接数量：" +sessions.values().size());
        //遍历所有连接
        for (Channel channel : sessions.values()) {
            InetSocketAddress insocket = (InetSocketAddress) channel.remoteAddress();
            String host = insocket.getAddress().getHostAddress();
            int port = insocket.getPort();
            try {
                byte[] value = zkclient.getData().forPath("/hosts/"+host+":"+port);
                String times = new String(value);

                long response = Long.parseLong(times.split("-")[1]);
                logger.info("hosts:{},value:{}","/hosts/"+host+":"+port,response);
                if(response <= minRespontime) {
                    minRespontime = response;
                    c= channel;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return c;
    }

}
